package com.test.base.netty_upgrade.fixlength;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Random;


@Slf4j
public class FixLengthClient {
    public static void main(String[] args) {
        send();
        System.out.println("finish");
    }

    public static byte[] fill_10_bytes(
            char c, int count) {
        byte[] bytes = new byte[10];
        // 将bytes进行赋值，默认为下划线
        Arrays.fill(bytes, (byte) '_');
        for (int i = 0; i < count; i++) {
            bytes[i] = (byte) c;
        }
        return bytes;
    }

    static void send() {
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(worker);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("sending...");
                            Random random = new Random();
                            char c = 'a';
                            ByteBuf buffer = ctx.alloc().buffer();
                            // 主动模拟粘包的情况，将10次消息拼接成为一次
                            for (int i = 0; i < 10; i++) {
                                buffer.writeBytes(fill_10_bytes(c, random.nextInt(10) + 1));
                                c++;
                            }
                            ctx.writeAndFlush(buffer);
                        }
                    });
                }
            });
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8080).sync();
        } catch (InterruptedException e) {
            log.error("client error", e);
        } finally {
            // 关闭worker
            worker.shutdownGracefully();
        }
    }
}
